package com.dm.wallpaper.library.abilityPackage;


import com.dm.wallpaper.library.ablility.WallpaperBoardCrashReportAbility;
import com.dm.wallpaper.library.customview.PxUtil;
import com.dm.wallpaper.library.database.Database;
import com.dm.wallpaper.library.helpers.TimeHelper;
import com.dm.wallpaper.library.items.Wallpaper;
import com.dm.wallpaper.library.preferences.Preferences;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import ohos.aafwk.ability.AbilityPackage;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.app.Context;
import ohos.bundle.AbilityInfo;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public abstract class WallpaperBoardApplication extends AbilityPackage implements ApplicationCallback {

    private static WallpaperBoardConfiguration mConfiguration;
    private static boolean mIsLatestWallpapersLoaded;
    private static WallpaperBoardApplication wallpaperBoardApplication;

    public static void setmConfiguration(WallpaperBoardConfiguration mConfiguration) {
        WallpaperBoardApplication.mConfiguration = mConfiguration;
    }

    public static void setWallpaperBoardApplication(WallpaperBoardApplication wallpaperBoardApplication) {
        WallpaperBoardApplication.wallpaperBoardApplication = wallpaperBoardApplication;
    }

    public static WallpaperBoardApplication getInstance() {
        return wallpaperBoardApplication;
    }

    public final static List<Wallpaper> newWallpapers = new ArrayList();
    Thread.UncaughtExceptionHandler mHandler;

    @Override
    public void onInitialize() {
        super.onInitialize();
        setWallpaperBoardApplication(this);
        Database.get();
        Preferences.get();
        PxUtil.initContext(this);
        setmConfiguration(onInit());
        ImageLoader.getInstance().init(getImageLoaderConfiguration(this));
        initData();
        mHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this::handleUncaughtException);
    }

    public static ImageLoaderConfiguration getImageLoaderConfiguration(Context context) {

        int MB = 1038336;
        return new ImageLoaderConfiguration.Builder(context)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .threadPoolSize(4)
                .tasksProcessingOrder(QueueProcessingType.FIFO)
                .diskCacheSize(256 * MB)
                .diskCache(new UnlimitedDiskCache(new File(
                        context.getCacheDir().toString() + "/uil-images")))
                .memoryCacheSize(8 * MB)
                .writeDebugLogs()
                .build();
    }


    public static WallpaperBoardConfiguration getConfig() {
        if (mConfiguration == null) {
            mConfiguration = new WallpaperBoardConfiguration();
        }
        return mConfiguration;
    }

    public static boolean isLatestWallpapersLoaded() {
        return mIsLatestWallpapersLoaded;
    }

    public static void setLatestWallpapersLoaded(boolean loaded) {
        mIsLatestWallpapersLoaded = loaded;
    }


    public abstract void initData();


    private void handleUncaughtException(Thread thread, Throwable throwable) {
        try {
            StringBuilder sb = new StringBuilder();
            SimpleDateFormat dateFormat = TimeHelper.getDefaultShortDateTimeFormat();
            String dateTime = dateFormat.format(new Date());
            sb.append("Crash Time : ").append(dateTime).append("\n");
            sb.append("Class Name : ").append(throwable.getClass().getName()).append("\n");
            sb.append("Caused By : ").append(throwable.toString()).append("\n");

            for (StackTraceElement element : throwable.getStackTrace()) {
                sb.append("\n");
                sb.append(element.toString());
            }

            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder().withBundleName(getBundleName()).withAbilityName(WallpaperBoardCrashReportAbility.class).build();
            intent.setOperation(operation);
            startAbility(intent, AbilityInfo.AbilityType.PAGE.ordinal());
        } catch (Exception e) {
            if (mHandler != null) {
                mHandler.uncaughtException(thread, throwable);
                return;
            }
        }
    }

}
